package com.biz.primus.ms.oms.dao.specification;

import com.biz.primus.common.utils.StringUtil;
import com.biz.primus.model.oms.enums.AllocationType;
import com.biz.primus.model.oms.enums.OrderDeliveryType;
import com.biz.primus.model.oms.vo.OrderQueryVo;
import com.biz.primus.ms.oms.dao.po.OmsOrder;
import com.google.common.collect.Lists;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.util.CollectionUtils;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.sql.Timestamp;
import java.time.LocalDate;
import java.util.List;

/**
 * @author LGJ
 * @date
 */
public class OmsOrderSpecification implements Specification<OmsOrder> {

    private OrderQueryVo orderQueryVo;

    public OmsOrderSpecification(OrderQueryVo orderQueryVo){
        this.orderQueryVo=orderQueryVo;
    }

    @Override
    public Predicate toPredicate(Root<OmsOrder> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
        List<Predicate> predicates = Lists.newArrayList();

        query.orderBy(cb.desc(root.get("createTimestamp")));

        if(!StringUtil.isNullOrEmpty(orderQueryVo.getDepotCode())){
            predicates.add(cb.equal(root.get("depotCode").as(String.class),orderQueryVo.getDepotCode()));
        }
        //如果allToday==true 忽略除了门店编号外的其他条件
        if(orderQueryVo.isAllToday()){
            predicates.add(cb.greaterThan(root.get("createTimestamp").as(Timestamp.class),Timestamp.valueOf(LocalDate.now().atStartOfDay())));
        }else{
            if(!CollectionUtils.isEmpty(orderQueryVo.getOrderState())){
                predicates.add(root.get("state").in(orderQueryVo.getOrderState()));
            }
    
            if(orderQueryVo.getOrderDeliveryTypes()!=null){
                predicates.add(cb.equal(root.get("deliveryType").as(OrderDeliveryType.class),orderQueryVo.getOrderDeliveryTypes()));
            }

            if(!StringUtil.isNullOrEmpty(orderQueryVo.getOrderCode())){
                predicates.add(cb.equal(root.get("orderCode").as(String.class),orderQueryVo.getOrderCode()));
            }

            if(orderQueryVo.getUserId()!=null){
                predicates.add(cb.equal(root.get("userId").as(Long.class),orderQueryVo.getUserId()));
            }

            if(orderQueryVo.getAllocationType()!=null){
                predicates.add(cb.equal(root.get("allocationType").as(AllocationType.class),orderQueryVo.getAllocationType()));
            }
        }


        query.where(predicates.toArray(new Predicate[predicates.size()]));
        return query.getRestriction();
    }
}
